# -*- coding: utf-8 -*-

import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://bpayment.maiduopay.com/Pay/GateWayTencent.aspx'
_ALI_GATEWAY = 'http://bpayment.maiduopay.com/Pay/GateWayAliPay.aspx'
_UNION_GATEWAY = 'http://bpayment.maiduopay.com/Pay/GateWayUnionPay.aspx'
_QUERY_GATEWAY = 'http://bpayment.maiduopay.com/Pay/ThridPayQuery.aspx'
# 接durotar 的银联和ｑｑ，找时间对接一下，优先级高一点
APP_CONF = {
    '3071': {
        'API_KEY': 'b079d234ff6d43a6b29efcc3527c3292'
    },
    '3151': {
        'API_KEY': 'bb5e9ec444b44906bed8ceb0ecd474b3'
    },
    '3331': {  # dwc 只跑QQ，原来的只跑支付宝
        'API_KEY': 'c62b415f192849b69c271284ed4ec1c5'
    },
    '3341': {  # loki 只跑QQ，原来的只跑支付宝
        'API_KEY': '2ff4b3b900d244e5808b5e57e338b20a'
    },
    '3351': {  # dwc 支付宝
        'API_KEY': '33c0ef61472141e6a18206f9dd437931'
    },
    '3621': {  # loki 支付宝
        'API_KEY': 'bc7e72e4753a4e4daaf1e3a727fcfb43'
    },
    '3631': {  # loki 支付宝
        'API_KEY': '2a8b1f85bd7e4111a0e2a83d683abed8'
    },
    '3641': {  # loki 支付宝
        'API_KEY': '5ef9031b2f974c03b14d8e76aee4c0e3'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _gen_md5_str(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(d, key):
    key = _gen_md5_str(key)
    s = 'app_id={}&pay_type={}&order_id={}&order_amt={}&notify_url={}&return_url={}&time_stamp={}&key={}'.format(
        d['app_id'], d['pay_type'], d['order_id'], d['order_amt'], d['notify_url'], d['return_url'], d['time_stamp'],
        key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_union_sign(d, key):
    key = _gen_md5_str(key)
    s = 'app_id={}&bank_code={}&order_id={}&order_amt={}&notify_url={}&return_url={}&time_stamp={}&key={}'.format(
        d['app_id'], d['bank_code'], d['order_id'], d['order_amt'], d['notify_url'], d['return_url'], d['time_stamp'],
        key
    )
    print s
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_query_sign(d, key):
    key = _gen_md5_str(key)
    s = 'app_id={}&order_id={}&time_stamp={}&key={}'.format(
        d['app_id'], d['order_id'], d['time_stamp'], key
    )
    _LOGGER.info("hongchuangpay quegenerate_query_sign str: %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_notify_sign(d, key):
    key = _gen_md5_str(key)
    s = 'app_id={}&order_id={}&pay_seq={}&pay_amt={}&pay_result={}&key={}'.format(
        d['app_id'], d['order_id'], d['pay_seq'], d['pay_amt'], d['pay_result'], key
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# 1=PC 扫码支付，2=手机 WAP 支付,3=手机公众 号支付(支付宝网关)，4=QQ 钱包 5=京东钱包
def create_qq_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    api_key = _get_api_key(mch_id)
    parameter_dict = {
        'app_id': mch_id,
        'pay_type': '4',
        'order_id': str(pay.id),
        'order_amt': str(pay_amount),
        'notify_url': '{}/pay/api/{}/hongchuangpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id),
        'return_url': '{}/pay/api/{}/hongchuangpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'goods_name': 'charge',
        'time_stamp': time.strftime("%Y%m%d%H%M%S", time.localtime()),
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("hongchuangpay create data : %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("hongchuangpay data rsp : %s", response.text)
    d = json.loads(response.text)
    return {'charge_info': d['pay_url']}


# 1=PC 扫码支付，2=手机 WAP 支付,3=支付宝网关
def create_ali_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    api_key = _get_api_key(mch_id)
    parameter_dict = {
        'app_id': mch_id,
        'pay_type': '2',
        'order_id': str(pay.id),
        'order_amt': str(pay_amount),
        'notify_url': '{}/pay/api/{}/hongchuangpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id),
        'return_url': '{}/pay/api/{}/hongchuangpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'goods_name': 'charge',
        'time_stamp': time.strftime("%Y%m%d%H%M%S", time.localtime()),
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("hongchuangpay create data : %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_ALI_GATEWAY, data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("hongchuangpay data rsp : %s, order_id: %s", response.text, pay.id)
    d = json.loads(response.text)
    return {'charge_info': d['pay_url']}


def create_union_charge(pay, pay_amount, info):
    # def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    api_key = _get_api_key(mch_id)
    parameter_dict = {
        'app_id': mch_id,
        'card_type': '1',  # 1:借记卡 2:贷记卡
        'user_type': '1',  # 1:个人 2:企业
        'channel_type': '2',  # 1:PC 2:手机
        # 'bank_code': 'YLBILL',
        'bank_code': 'QUICK',
        'order_id': str(pay.id),
        'order_amt': str(pay_amount),
        'notify_url': '{}/pay/api/{}/hongchuangpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id),
        'return_url': '{}/pay/api/{}/hongchuangpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'goods_name': 'charge',
        'time_stamp': time.strftime("%Y%m%d%H%M%S", time.localtime()),
    }
    parameter_dict['sign'] = generate_union_sign(parameter_dict, api_key)
    _LOGGER.info("hongchuangpay create data : %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_UNION_GATEWAY, data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("hongchuangpay data rsp : %s", response.text)
    d = json.loads(response.text)
    return {'charge_info': d['pay_url']}


def create_charge(pay, pay_amount, info):
    service = info['service']
    if service == 'qq':
        return create_qq_charge(pay, pay_amount, info)
    elif service == 'alipay':
        return create_ali_charge(pay, pay_amount, info)
    else:
        return create_union_charge(pay, pay_amount, info)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("hongchuangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# ok
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("hongchuangpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('hongchuangpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay or pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = str(data['pay_result'])
    mch_id = pay.mch_id
    trade_no = data['pay_seq']
    total_fee = data['pay_amt']
    total_fee = float(total_fee)

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    # 20—支付成功， 其它为未知
    if trade_status == '20':
        _LOGGER.info('hongchuangpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('app_id', app_id),
        ('order_id', str(pay_order.id)),
        ('time_stamp', time.strftime("%Y%m%d%H%M%S", time.localtime())),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info("hongchuangpay query data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("hongchuangpay query rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['pay_result'])
        trade_no = data['pay_seq']
        total_fee = float(data['pay_amt'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 20—支付成功， 其它为未知
        if trade_status == '20':
            _LOGGER.info('hongchuangpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('hongchuangpay data error, status_code: %s', response.status_code)
